# -*- coding: utf-8 -*-
"""
Markdown导出器
"""
from typing import Dict
import os
from .base_exporter import BaseExporter

class MarkdownExporter(BaseExporter):
    """Markdown导出器"""
    
    def export(self, dict_data: Dict, file_path: str) -> bool:
        """
        导出为Markdown格式
        
        Args:
            dict_data: 数据库字典数据
            file_path: 导出文件路径
            
        Returns:
            导出是否成功
        """
        try:
            if not self._validate_file_path(file_path):
                return False
            
            # 生成Markdown内容
            content = self._generate_markdown_content(dict_data)
            
            # 写入文件
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(content)
            
            return True
            
        except Exception as e:
            print(f"Markdown导出失败: {e}")
            return False
    
    def _generate_markdown_content(self, dict_data: Dict) -> str:
        """生成Markdown内容"""
        content = []
        
        # 标题
        db_info = dict_data.get('database_info', {})
        db_name = db_info.get('database_name', '')
        
        content.append("# MySQL数据库字典")
        content.append("")
        
        if db_name:
            content.append(f"**数据库名称:** {db_name}")
            content.append("")
        
        # 摘要信息
        content.append("## 数据库摘要")
        content.append("")
        
        summary = self._get_export_summary(dict_data)
        summary_data = [
            ("导出时间", summary['export_time']),
            ("数据库名称", summary['database_name']),
            ("数据库版本", summary['database_version']),
            ("字符集", db_info.get('charset', '')),
            ("表总数", str(summary['total_tables'])),
            ("字段总数", str(summary['total_columns'])),
            ("索引总数", str(summary['total_indexes']))
        ]
        
        for label, value in summary_data:
            content.append(f"- **{label}:** {value}")
        
        content.append("")
        
        # 表列表
        content.append("## 表列表")
        content.append("")
        
        # 创建表列表表格
        table_headers = ["表名", "表注释", "字段数", "索引数"]
        content.append("| " + " | ".join(table_headers) + " |")
        content.append("| " + " | ".join(["---"] * len(table_headers)) + " |")
        
        for table in dict_data.get('tables', []):
            row = [
                table['name'],
                self._clean_text_for_markdown(table.get('comment', '')),
                str(len(table.get('columns', []))),
                str(len(table.get('indexes', [])))
            ]
            content.append("| " + " | ".join(row) + " |")
        
        content.append("")
        
        # 表结构详情
        tables = dict_data.get('tables', [])
        total_tables = len(tables)
        
        for i, table in enumerate(tables):
            if self.check_cancel():
                break
            
            self._add_table_section(content, table)
            
            # 更新进度
            progress = int((i + 1) / total_tables * 100)
            self.update_progress(progress, f"正在导出表: {table['name']}")
        
        return "\n".join(content)
    
    def _add_table_section(self, content: list, table: Dict):
        """添加表结构章节"""
        # 表标题
        table_name = table['name']
        content.append(f"## 表: {table_name}")
        content.append("")
        
        # 表注释
        if table.get('comment'):
            cleaned_comment = self._clean_text_for_markdown(table['comment'])
            content.append(f"**表注释:** {cleaned_comment}")
            content.append("")
        
        # 字段信息
        content.append("### 字段信息")
        content.append("")
        
        columns = table.get('columns', [])
        if columns:
            # 创建字段表格
            field_headers = ["字段名", "数据类型", "长度", "精度", "小数位", "是否为空", "默认值", "字段注释"]
            content.append("| " + " | ".join(field_headers) + " |")
            content.append("| " + " | ".join(["---"] * len(field_headers)) + " |")
            
            for column in columns:
                row = [
                    column['name'],
                    column['type_display'],
                    str(column.get('length', '')),
                    str(column.get('precision', '')),
                    str(column.get('scale', '')),
                    "是" if column['nullable'] else "否",
                    str(column.get('default', '')),
                    self._clean_text_for_markdown(column.get('comment', ''))
                ]
                content.append("| " + " | ".join(row) + " |")
            
            content.append("")
        
        # 索引信息
        indexes = table.get('indexes', [])
        if indexes:
            content.append("### 索引信息")
            content.append("")
            
            # 创建索引表格
            index_headers = ["索引名", "索引类型", "是否唯一", "字段列表"]
            content.append("| " + " | ".join(index_headers) + " |")
            content.append("| " + " | ".join(["---"] * len(index_headers)) + " |")
            
            for index in indexes:
                row = [
                    index['name'],
                    index['type'],
                    "是" if index['unique'] else "否",
                    ', '.join(index['columns'])
                ]
                content.append("| " + " | ".join(row) + " |")
            
            content.append("")
        
        # 添加分隔线
        content.append("---")
        content.append("")
    
    def _clean_text_for_markdown(self, text: str) -> str:
        """
        清理文本中的换行符，使其适合在Markdown表格中显示
        
        Args:
            text: 原始文本
            
        Returns:
            清理后的文本
        """
        if not text:
            return ''
        
        # 替换各种换行符为HTML换行标签
        cleaned = text.replace('\r\n', '<br>').replace('\n', '<br>').replace('\r', '<br>')
        
        # 替换多个连续的<br>标签为单个<br>
        import re
        cleaned = re.sub(r'(<br>\s*)+', '<br>', cleaned)
        
        # 去除首尾的<br>标签和空格
        cleaned = cleaned.strip()
        if cleaned.startswith('<br>'):
            cleaned = cleaned[4:]
        if cleaned.endswith('<br>'):
            cleaned = cleaned[:-4]
        
        return cleaned
